"use client";
import { userRegisterUsingPost } from "@/api/userController";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import {
  LoginForm,
  ProFormInstance,
  ProFormText,
} from "@ant-design/pro-components";
import { message } from "antd";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import React, { useRef } from "react";
import "./index.css";

/**
 * 用户注册
 * @returns
 */
export const RegisterPage: React.FC = () => {
  const router = useRouter();
  const formRef = useRef<ProFormInstance | undefined>(undefined);
  const [messageApi, contextHolder] = message.useMessage();

  const submit = async (values: API.UserRegisterRequest) => {
    try {
      const res = await userRegisterUsingPost(values);
      if (res.data) {
        messageApi.success("注册成功");
        router.replace("/user/login");
        formRef?.current?.resetFields();
      }
    } catch (e: any) {
      messageApi.error("注册失败" + e.message);
    }
  };
  return (
    <div className="loginPage">
      {contextHolder}
      <LoginForm
        logo={
          <Image src="/assets/logo.png" alt="logo" height={44} width={44} />
        }
        title="题库系统"
        subTitle="题目汇总网站"
        submitter={{ searchConfig: { submitText: "注册" } }}
        onFinish={(values) => {
          submit(values);
        }}
      >
        <ProFormText
          name="userAccount"
          fieldProps={{
            size: "large",
            prefix: <UserOutlined />,
          }}
          placeholder={"请输入用户账号"}
          rules={[
            {
              required: true,
              message: "请输入正确的账号!",
            },
          ]}
        />
        <ProFormText.Password
          name="userPassword"
          fieldProps={{
            size: "large",
            prefix: <LockOutlined />,
          }}
          placeholder={"请输入密码"}
          rules={[
            {
              required: true,
              message: "请输入正确的密码!",
            },
          ]}
        />
        <ProFormText.Password
          name="checkPassword"
          fieldProps={{
            size: "large",
            prefix: <LockOutlined />,
          }}
          placeholder={"请确认密码"}
          rules={[
            {
              required: true,
              message: "请输入正确的密码!",
            },
          ]}
        />
        <div style={{ marginBlockEnd: 10, float: "right" }}>
          已有账号？
          <Link href="/user/login">去登录</Link>
        </div>
      </LoginForm>
    </div>
  );
};
export default RegisterPage;
